var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

//存储用户对应的websocket连接
var users = {};
io.on('connection', function (socket) {
  users[socket.handshake.query.userId] = socket;
  socket.on('message', function (msg) {
    console.log(msg);

    //取出消息要发送给哪个用户
    var receiver = msg['receiver'];
    //取出接收人的websocket连接
    var receiverSocket = users[receiver];

    if (!receiverSocket) {
      console.log("未发现在线用户:" + receiver);
      return;
    }

    //发送给接收人
    receiverSocket.emit('message', msg);
  });
});

http.listen(port, function () {
  console.log('listening on *:' + port);
});
